//
//  CLComposeTextView.swift
//  CLWeibo
//
//  Created by 陈亮 on 16/7/18.
//  Copyright © 2016年 陈亮. All rights reserved.
//

import UIKit

//实时看到xib上的属性方式
@IBDesignable
class CLComposeTextView: UITextView {

    //懒加载控件
    private lazy var placeHolderLabel:UILabel = {
        
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(12)
        label.text = "jimmy,i love you"
        label.numberOfLines = 0
        label.textColor = UIColor.grayColor()
        return label
    }()
    
    //占位文字
    @IBInspectable var placeHolder: String? {
        didSet {
            placeHolderLabel.text = placeHolder
        }
    }
    
    //重写font 
    override var font :UIFont? {
        didSet {
            if font == nil {
                return
            }
            placeHolderLabel.font = font
            
        }
    }
    //重写text
    override var text:String? {
        didSet {
            placeHolderLabel.text = text
        }
    }
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func setUpUI(){
        //监听textView文字改变的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChange", name: UITextViewTextDidChangeNotification, object: nil)
        //添加控件
        addSubview(placeHolderLabel)
        //设置约束
        placeHolderLabel.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .Leading, relatedBy: .Equal, toItem: self, attribute: .Leading, multiplier: 1, constant: 5))
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 8))
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .Width, relatedBy: .Equal, toItem: self, attribute: .Width, multiplier: 1, constant: -10))
        
    }
    //监听textView文字改变的方法
    @objc private func textChange() {
        
        placeHolderLabel.hidden = hasText()
    }
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    
}